//
//  HOReassignRepairerViewController.m
//  微度报修
//
//  Created by foguo-mac-1 on 7/5/16.
//  Copyright © 2016 WeiDu. All rights reserved.
//

#import "HOReassignRepairerViewController.h"
#import "HOConstants.h"
#import "UIImageView+WebCache.h"
#import "HOImageMgr.h"
#import "HOEditView.h"
#import "HOButton.h"
#import "HOAssignViewController.h"
#import "HOUtils.h"

@interface HOReassignRepairerViewController ()<HOAssignViewControllerDelegate>
{
	NSInteger selectedReason;
}

@property(nonatomic, retain)HOEditView *reasonEditView;
@end

@implementation HOReassignRepairerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
	[self initTableView];
	[self initSubviews];
	[self initTableViewFooterViewWithTitle:NSLocalizedString(@"确认提交", @"确认提交")];
	[self registerTapGesture];
	[self registerKeyboard];
	[self requestData];
}

- (void)requestData
{
	if(self.entity.userId > 0)
	[self sendRequestWithParams:@{kHO_FIELD_Action:kHO_ACTION_GetRepairmanInfo,
								  kHO_FIELD_UserId:[NSNumber numberWithInt:self.entity.userId]}];
}

- (void)didClickFooterButton:(UIButton *)btn
{
	NSString *content = [self getTrimingCharaFromTextView:[self.reasonEditView getTextView]];
	if(content == nil)
	{
		[super popupHintView:NSLocalizedString(@"请填写更换维修人理由", @"请填写更换维修人理由")];
		return;
	}
	self.view.userInteractionEnabled = NO;
	[self sendRequestWithParams:@{kHO_FIELD_Action:kHO_ACTION_ReAssignFault,
								  kHO_FIELD_OrderId:[NSNumber numberWithInt:self.orderId],
								  kHO_FIELD_AssignId:[NSNumber numberWithInt:self.entity.userId],
								  kHO_FIELD_RecordStatus:[NSNumber numberWithInteger:selectedReason],
								  kHO_FIELD_Content:content}];
}

- (void)didSelectRepairer:(HORepairerEntity *)entity
{
	self.entity = entity;
	[baseTableview reloadData];
}

- (void)initSubviews
{
	self.reasonEditView = [[[HOEditView alloc] initWithFrame:CGRectMake(0,
																  0,
																  self.view.frame.size.width,
																  134)] autorelease];
	self.reasonEditView.limitedCount = 120;
//	self.reasonEditView.delegate = self;
//	self.reasonEditView.layer.cornerRadius = 5;
	[self.reasonEditView.layer setMasksToBounds:YES];
	[self.reasonEditView setPlaceHolder:NSLocalizedString(@"填写更换维修人理由", @"填写更换维修人理由")];
	[self.reasonEditView getTextView].returnKeyType = UIReturnKeySend;
}

- (void)viewWillAppear:(BOOL)animated
{
	[super viewWillAppear:animated];
	[self setNavigationItemTitle:NSLocalizedString(@"更换维修人", @"更换维修人")];
//	[self displayRightButtonItemWithTitle:NSLocalizedString(@"选择维修人", @"选择维修人")];
}

- (void)onKeyboardWillShow:(NSNotification *)notification
{
	[super onKeyboardWillShow:notification];
	[baseTableview scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:2] atScrollPosition:UITableViewScrollPositionTop animated:YES];

}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
	[self hideKeyboard];
}

- (void)rightButtonItemDidClick
{
	HOAssignViewController *viewCtrl = [[HOAssignViewController alloc] init];
	viewCtrl.delegate = self;
	viewCtrl.departmentId = self.departmentId;
	[self.navigationController pushViewController:viewCtrl animated:YES];
	[viewCtrl release];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)hideKeyboard
{
	[[self.reasonEditView getTextView] resignFirstResponder];
}

#pragma mark - -- UITableViewDelegate/UITableViewDataResource implement methods
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	if(indexPath.section == 0)
	{
		UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
		UILabel *reasonLbl4 = (UILabel *)[cell viewWithTag:119];
		return reasonLbl4.frame.size.height + reasonLbl4.frame.origin.y + 2 * HO_HORIZONAL_PADDING;
	}
	else if(indexPath.section == 1)
	{
		return 60;
	}
    return 134;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	return 1;
}


- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
	if(section == 0)
		return [HOUtils defaultOnePixelConversion];
    return SECTION_PADDING / 2;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if(indexPath.section == 1)
	{
		[self rightButtonItemDidClick];
	}
}

- (void)didSelectReason1:(id)sender
{
	selectedReason = 0;
	[baseTableview reloadData];
}

- (void)didSelectReason2:(id)sender
{
	selectedReason = 1;
	[baseTableview reloadData];
}

- (void)didSelectReason3:(id)sender
{
	selectedReason = 2;
	[baseTableview reloadData];
}

- (void)didSelectReason4:(id)sender
{
	selectedReason = 3;
	[baseTableview reloadData];
}
#pragma mark
- (HOButton *)createButtonWithY:(CGFloat)y withSel:(SEL)selector
{
	HOButton *btn = [[[HOButton alloc]
					 initWithFrame:CGRectMake(HO_HORIZONAL_PADDING,
											  y,
											  12,
											  12)] autorelease];
	[btn setBackgroundImage:[UIImage imageNamed:@"ic_chakanzhuangtai_hui"] forState:UIControlStateNormal];
	[btn setBackgroundImage:[UIImage imageNamed:@"ic_chakanzhuangtai"] forState:UIControlStateSelected];
	[btn setBackgroundImage:[UIImage imageNamed:@"ic_chakanzhuangtai"] forState:UIControlStateHighlighted];
	[btn addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
	return btn;
}

- (void)updateBtn:(HOButton *)btn
{
	NSInteger tag = btn.tag - 550;
	if(tag == selectedReason)
	{
		[btn setBackgroundImage:[UIImage imageNamed:@"ic_chakanzhuangtai"] forState:UIControlStateNormal];
		[btn setBackgroundImage:[UIImage imageNamed:@"ic_chakanzhuangtai_hui"] forState:UIControlStateSelected];
		[btn setBackgroundImage:[UIImage imageNamed:@"ic_chakanzhuangtai_hui"] forState:UIControlStateHighlighted];
	}
	else
	{
		[btn setBackgroundImage:[UIImage imageNamed:@"ic_chakanzhuangtai_hui"] forState:UIControlStateNormal];
		[btn setBackgroundImage:[UIImage imageNamed:@"ic_chakanzhuangtai"] forState:UIControlStateSelected];
		[btn setBackgroundImage:[UIImage imageNamed:@"ic_chakanzhuangtai"] forState:UIControlStateHighlighted];
	}
}

- (CGSize)getSizeWithContent:(NSString *)content withFont:(UIFont *)font
{
	CGSize size = CGSizeZero;
	if(IS_LESSTHAN_IOS7)
	{
		size = [content sizeWithFont:font];
	}
	else
	{
		size = [content sizeWithAttributes:@{ NSFontAttributeName:font}];
	}
	return size;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	if(indexPath.section == 0)
	{
		static NSString *UIRepairerReasonTableViewCell = @"UIRepairerReasonTableViewCell";
		UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:UIRepairerReasonTableViewCell];
		if(cell == nil)
		{
			cell = [[[UITableViewCell alloc]
					 initWithStyle:UITableViewCellStyleDefault
					 reuseIdentifier: UIRepairerReasonTableViewCell] autorelease];
		}
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
		UILabel *lbl = (UILabel *)[cell viewWithTag:115];
		if(lbl == nil)
		{
			lbl = [[[UILabel alloc]
				   initWithFrame:CGRectMake(HO_HORIZONAL_PADDING,
											23,
											tableView.frame.size.width - 2 * HO_HORIZONAL_PADDING,
											22)] autorelease];
			lbl.textColor = TEXT_COLOR_666666;
			lbl.font = [UIFont systemFontOfSize:15];
			[cell.contentView addSubview:lbl];
			lbl.text = NSLocalizedString(@"当前维修状态是：", @"当前维修状态是：");
		}
		
		UIButton *reasonLbl1 = (UIButton *)[cell viewWithTag:116];
		if(reasonLbl1 == nil)
		{
			reasonLbl1 = [[[UIButton alloc]
					initWithFrame:CGRectMake(30,
											 lbl.frame.origin.y + lbl.frame.size.height + 15,
											 tableView.frame.size.width - 40,
											 22)] autorelease];
			reasonLbl1.tag = 116;
			reasonLbl1.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
//			reasonLbl1.layer.borderWidth = 1;
			reasonLbl1.titleLabel.font = [UIFont systemFontOfSize:15];
			reasonLbl1.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
			[reasonLbl1 addTarget:self action:@selector(didSelectReason1:) forControlEvents:UIControlEventTouchUpInside];
			[cell.contentView addSubview:reasonLbl1];
			[reasonLbl1 setTitle:NSLocalizedString(@"任务还未处理， 跟换其他维修人员处理", @"任务还未处理， 跟换其他维修人员处理") forState:UIControlStateNormal];
			[reasonLbl1.titleLabel sizeToFit];
			[reasonLbl1 setTitleColor:TEXT_COLOR_666666 forState:UIControlStateNormal];
			[reasonLbl1 setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
			[reasonLbl1 setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
		}
		
		HOButton *btn1 = (HOButton *)[cell viewWithTag:550];
		if(btn1 == nil)
		{
			btn1 = [self createButtonWithY:(reasonLbl1.frame.origin.y + 2) withSel:@selector(didSelectReason1:)];
			[cell.contentView addSubview:btn1];
			btn1.tag = 550;
		}
		[self updateBtn:btn1];
		
		UIButton *reasonLbl2 = (UIButton *)[cell viewWithTag:117];
		if(reasonLbl2 == nil)
		{
			reasonLbl2 = [[[UIButton alloc]
						   initWithFrame:CGRectMake(30,
													reasonLbl1.frame.origin.y + reasonLbl1.frame.size.height + 11,
													tableView.frame.size.width - 40,
													22)] autorelease];
			reasonLbl2.tag = 117;
			[reasonLbl2 addTarget:self action:@selector(didSelectReason2:) forControlEvents:UIControlEventTouchUpInside];
			reasonLbl2.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
			reasonLbl2.titleLabel.font = [UIFont systemFontOfSize:15];
			reasonLbl2.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
			[cell.contentView addSubview:reasonLbl2];
			[reasonLbl2 setTitle:NSLocalizedString(@"任务分配错误， 不是本人维修范围", @"任务分配错误， 不是本人维修范围") forState:UIControlStateNormal];
			[reasonLbl2.titleLabel sizeToFit];
			[reasonLbl2 setTitleColor:TEXT_COLOR_666666 forState:UIControlStateNormal];
			[reasonLbl2 setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
			[reasonLbl2 setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
		}
		
		HOButton *btn2 = (HOButton *)[cell viewWithTag:551];
		if(btn2 == nil)
		{
			btn2 = [self createButtonWithY:(reasonLbl2.frame.origin.y + 2) withSel:@selector(didSelectReason2:)];
			[cell.contentView addSubview:btn2];
			btn2.tag = 551;
		}
		[self updateBtn:btn2];
		
		
		UIButton *reasonLbl3 = (UIButton *)[cell viewWithTag:118];
		if(reasonLbl3 == nil)
		{
			reasonLbl3 = [[[UIButton alloc]
						   initWithFrame:CGRectMake(30,
													reasonLbl2.frame.origin.y + reasonLbl2.frame.size.height + 15,
													tableView.frame.size.width - 40,
													22)] autorelease];
			reasonLbl3.tag = 118;
			reasonLbl3.titleLabel.font = [UIFont systemFontOfSize:15];
			reasonLbl3.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
			[cell.contentView addSubview:reasonLbl3];
			reasonLbl3.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
			[reasonLbl3 setTitle:NSLocalizedString(@"任务已经部分处理， 下一步共组需要其他维修人员记录处理", @"任务已经部分处理， 下一步共组需要其他维修人员记录处理") forState:UIControlStateNormal];
			[reasonLbl3 addTarget:self action:@selector(didSelectReason3:) forControlEvents:UIControlEventTouchUpInside];
			[reasonLbl3.titleLabel sizeToFit];
			[reasonLbl3 setTitleColor:TEXT_COLOR_666666 forState:UIControlStateNormal];
			[reasonLbl3 setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
			[reasonLbl3 setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
		}
		
		HOButton *btn3 = (HOButton *)[cell viewWithTag:552];
		if(btn3 == nil)
		{
			btn3 = [self createButtonWithY:(reasonLbl3.frame.origin.y + 2) withSel:@selector(didSelectReason3:)];
			[cell.contentView addSubview:btn3];
			btn3.tag = 552;
		}
		[self updateBtn:btn3];
		
		
		UIButton *reasonLbl4 = (UIButton *)[cell viewWithTag:119];
		if(reasonLbl4 == nil)
		{
			reasonLbl4 = [[[UIButton alloc]
						   initWithFrame:CGRectMake(30,
													reasonLbl3.frame.origin.y + reasonLbl3.frame.size.height + 15,
													tableView.frame.size.width - 40,
													22)] autorelease];
			reasonLbl4.titleLabel.font = [UIFont systemFontOfSize:15];
			[cell.contentView addSubview:reasonLbl4];
			reasonLbl4.tag = 119;
			reasonLbl4.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
			[reasonLbl4 addTarget:self action:@selector(didSelectReason4:) forControlEvents:UIControlEventTouchUpInside];
			reasonLbl4.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
			[reasonLbl4 setTitle:NSLocalizedString(@"任务无法完成，需要其他维修人员继续处理", @"任务无法完成，需要其他维修人员继续处理") forState:UIControlStateNormal];
			[reasonLbl4.titleLabel sizeToFit];
			[reasonLbl4 setTitleColor:TEXT_COLOR_666666 forState:UIControlStateNormal];
			[reasonLbl4 setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
			[reasonLbl4 setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
		}
		
		HOButton *btn4 = (HOButton *)[cell viewWithTag:553];
		if(btn4 == nil)
		{
			btn4 = [self createButtonWithY:(reasonLbl4.frame.origin.y + 2) withSel:@selector(didSelectReason4:)];
			[cell.contentView addSubview:btn4];
			btn4.tag = 553;
		}
		[self updateBtn:btn4];
		return cell;
		
	}
	if(indexPath.section == 1 && indexPath.row == 0)
	{
		static NSString *UIRepairerTableViewCell = @"UIRepairerTableViewCell";
		UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:UIRepairerTableViewCell];
		if(cell == nil)
		{
			cell = [[[UITableViewCell alloc]
					 initWithStyle:UITableViewCellStyleDefault
					 reuseIdentifier: UIRepairerTableViewCell] autorelease];
		}
		cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
		UIImageView *headerImgView = (UIImageView *)[cell viewWithTag:112];
		if(headerImgView == nil)
		{
			headerImgView = [[[UIImageView alloc]
							  initWithFrame:CGRectMake(HO_HORIZONAL_PADDING,
													   7,
													   34,
													   34)] autorelease];
			headerImgView.tag = 112;
			[headerImgView.layer setCornerRadius:17];
			[cell.contentView addSubview:headerImgView];
			[headerImgView.layer setMasksToBounds:YES];
		}
		[headerImgView sd_setImageWithURL:[NSURL URLWithString:self.entity.headPic] placeholderImage:[[HOImageMgr sharedInstance] getDefaultImage]];
		
		UILabel *workStatusLbl = (UILabel *)[cell viewWithTag:1123];
		if(workStatusLbl == nil)
		{
			workStatusLbl = [[[UILabel alloc]
							  initWithFrame:CGRectMake(12,
													   37,
													   40,
													   22)] autorelease];
			workStatusLbl.tag = 1123;
			[cell.contentView addSubview:workStatusLbl];
			workStatusLbl.textColor = TEXT_COLOR_181818;
			workStatusLbl.font = [UIFont systemFontOfSize:12];
		}
		if(self.entity.isWorking)
		{
			workStatusLbl.text = @"[在线]";
			workStatusLbl.textColor = UIColorFromRGB(0x0b7f1e);
		}
		else
		{
			workStatusLbl.text = @"[离线]";
			workStatusLbl.textColor = UIColorFromRGB(0xcdcdcd);
		}
		
		
		UILabel *nameLbl = (UILabel *)[cell viewWithTag:145];
		if(nameLbl == nil)
		{
			nameLbl = [[[UILabel alloc]
						initWithFrame:CGRectMake(54,
												 8,
												 tableView.frame.size.width - 54,
												 22)] autorelease];
			nameLbl.tag = 145;
			[cell.contentView addSubview:nameLbl];
			nameLbl.textColor = TEXT_COLOR_181818;
			nameLbl.font = [UIFont systemFontOfSize:15];
		}
//		nameLbl.layer.borderWidth = 1;
		NSString *hopeName = [HOUtils getValideString:self.entity.HopeName];

		if(self.entity.userId == 0)
		{
			hopeName = NSLocalizedString(@"未分配维修人员，请点击分配！", @"未分配维修人员，请点击分配！");
		}
		else
		{
			if(hopeName == nil || hopeName.length == 0)
				hopeName = self.entity.userName;
		}
		nameLbl.text = hopeName;
		
		UILabel *levelLbl = (UILabel *)[cell viewWithTag:116];
		if(levelLbl == nil)
		{
			levelLbl = [[[UILabel alloc]
						 initWithFrame:CGRectMake(120,
												  8,
												  200,
												  22)] autorelease];
			levelLbl.tag = 116;
			[cell.contentView addSubview:levelLbl];
			levelLbl.textColor = TEXT_COLOR_181818;
			levelLbl.font = [UIFont systemFontOfSize:13];
		}
		levelLbl.text = [HOUtils getValideString:self.entity.level];
		
		levelLbl.frame = CGRectMake(nameLbl.frame.origin.x + nameLbl.frame.size.width + HO_HORIZONAL_PADDING,
								   8,
								   100,
								   22);
		
		UILabel *ratingLlb = (UILabel *)[cell viewWithTag:117];
		if(ratingLlb == nil)
		{
			ratingLlb = [[[UILabel alloc]
						  initWithFrame:CGRectMake(nameLbl.frame.origin.x,
												   32,
												   200,
												   22)] autorelease];
			ratingLlb.tag = 117;
			[cell.contentView addSubview:ratingLlb];
			ratingLlb.textColor = TEXT_COLOR_666666;
			ratingLlb.font = [UIFont systemFontOfSize:13];
		}
		int apprise = ((int)(self.entity.appraise + 1));
		
		ratingLlb.text = [NSString stringWithFormat:@"%@ %d", NSLocalizedString(@"评分：", @"评分："), MIN(apprise, 5)];
		
		
		HOButton *iconImgView = (HOButton *)[cell viewWithTag:118];
		if(iconImgView == nil)
		{
			UIImage *image = [UIImage imageNamed:@"ic-chakanzhuangtai_dadianhua"];
			iconImgView = [[[HOButton alloc]
							initWithFrame:CGRectMake(tableView.frame.size.width - 35 - 35,
													 (60 - 35) / 2,
													 35,
													 35)] autorelease];
			iconImgView.tag = 118;
			[iconImgView setBackgroundImage:image forState:UIControlStateNormal];
			//			iconImgView.layer.borderWidth = 1;
			[iconImgView addTarget:self action:@selector(callPhoneNumber:) forControlEvents:UIControlEventTouchUpInside];
			[cell.contentView addSubview:iconImgView];
		}
		
//		if(self.entity.virtualCellPhone == nil || self.entity.virtualCellPhone.length < 2)
//		{
//			iconImgView.hidden = YES;
//		}
//		else
//		{
//			iconImgView.hidden = NO;
//		}
		
		return cell;
	}
	else if(indexPath.section == 2)
	{
		static NSString *UIRepairerTableViewCell = @"UIRepairerTableViewCell";
		UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:UIRepairerTableViewCell];
		if(cell == nil)
		{
			cell = [[[UITableViewCell alloc]
					 initWithStyle:UITableViewCellStyleDefault
					 reuseIdentifier: UIRepairerTableViewCell] autorelease];
		}
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
		HOEditView *editView = (HOEditView *)[cell viewWithTag:112];
		if(editView == nil)
		{
			editView = self.reasonEditView;
			self.reasonEditView.tag = 112;
			[cell.contentView addSubview:editView];
		}
		return cell;
	}
	return nil;
}

- (void)callPhoneNumber:(id)sender
{
	[HOUtils callPhoneNumber:self.entity.virtualCellPhone];
}

- (void)requestDidSuccessWithResponse:(HOBaseResponseEntity *)response
{
	if([response isEqualAction:kHO_ACTION_ReAssignFault])
	{
		self.view.userInteractionEnabled = NO;
		[self sendCommand:kHO_CMD_Report_Detail_Changed data:nil];
		[self popupHintView:NSLocalizedString(@"提交成功", @"提交成功") inTime:1.5 needCallback:YES];
	}
	else if([response isEqualAction:kHO_ACTION_GetRepairmanInfo])
	{
		[self.entity parseDic:response.dataNode];
		[baseTableview reloadData];
	}
}

- (void)hintDidHide
{
	self.view.userInteractionEnabled = YES;
	[self goBack];
}

- (void)dealloc
{
	self.reasonEditView = nil;
	[super dealloc];
}
#pragma mark -- tool
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
